package com.fast.develop.dm.core.xml.generator;

import cn.hutool.core.util.XmlUtil;
import com.fast.develop.dm.meta.MetaDomainModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author 莫寅
 * @createTime 2022-06-05 01:25
 * @desc：
 */
public class ClassGenerator {

    private String entityName;
    private String tableName;
    private String dynamicUpdate;
    private String dynamicInsert;
    private MetaDomainModel metaDomainModel;

    public ClassGenerator(MetaDomainModel metaDomainModel) {
        this.entityName = metaDomainModel.getName();
        this.tableName = metaDomainModel.getTableName();
        this.dynamicUpdate = "true";
        this.dynamicInsert = "true";
        this.metaDomainModel = metaDomainModel;
    }

    /**
     *
     * <class entity-name="Book_0" dynamic-update="true" dynamic-insert="true">
     * @return
     */
    public String generate(){
        Document document = XmlUtil.createXml();


        document.setXmlStandalone(true);



        Element hibernateMappingElement = document.createElement("hibernate-mapping");
        document.appendChild(hibernateMappingElement);


        Element element = document.createElement("class");
        element.setAttribute("entity-name", entityName);
        element.setAttribute("table", tableName);
        element.setAttribute("dynamic-update", dynamicUpdate);
        element.setAttribute("dynamic-insert", dynamicInsert);

        hibernateMappingElement.appendChild(element);

        new IdGenerator(document, metaDomainModel).generate(element);

        metaDomainModel.getFields().stream()
                .filter(metaField -> !metaField.getPrimaryKey())
                .forEach(metaField -> {
                    new PropertyGenerator(document, metaField).generate(element);
                });

        return XmlUtil.toStr(document);
    }
}
